package com.xw.service.sysconfig;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.google.common.collect.Maps;
import com.xw.common.Const;
import com.xw.dao.SysVerificationCodeMapper;
import com.xw.model.SysVerificationCode;
import com.xw.model.sdk.AliSms;
import com.xw.model.sdk.UcpaasJson;
import com.xw.service.common.impl.BaseServiceImpl;
import com.xw.service.tool.alisms.AliSmsService;
import com.xw.service.tool.ucpaas.UcpaasService;
import com.xw.util.AppUtil;
import com.xw.util.JsonData;
import com.xw.util.PropertiesUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

@Service
@Transactional(rollbackFor = Exception.class)
public class VerificationCodeServiceImpl extends BaseServiceImpl<SysVerificationCode> implements VerificationCodeService {

    @Resource
    private SysVerificationCodeMapper verificationCodeMapper;
    @Resource
    private UcpaasService ucpaasService;
    @Resource
    private AliSmsService aliSmsService;

    //云之讯
    private static final String TEMPLATE_ID = PropertiesUtil.getProperty("SEND_CODE_TEMPLATE_ID");

    @Override
    public Map checkVerificationCode(String phone, String vcId, String codeNum) {
        Map map = Maps.newHashMap();
        //判断验证码是否可用
        SysVerificationCode code = verificationCodeMapper.selectByPrimaryKey(vcId);
        if (code == null) {
            //验证码不存在
            map.put("code",804);
            map.put("msg","验证码不存在");
            return map;
        }
        if (!(phone.equals(code.getVcPhone()))) {
            //是否是该手机发的验证码
            map.put("code",805);
            map.put("msg","手机号验证码不匹配");
            return map;
        }
        if (!codeNum.equals(code.getVcCode())) {
            //验证码输入有误
            map.put("code",806);
            map.put("msg","验证码输入有误");
            return map;
        }
        if (code.getVcStatus() == 2) {
            //已使用
            map.put("code",807);
            map.put("msg","验证码无效");
            return map;
        }
        if (code.getValidTime().getTime() < new Date().getTime()) {
            //已过期
            //修改验证码状态为已使用
            code = new SysVerificationCode();
            code.setVcId(vcId);
            code.setVcStatus(2);
            verificationCodeMapper.updateByPrimaryKeySelective(code);
            map.put("code",808);
            map.put("msg","验证码过期");
            return map;
        }
        return JsonData.success();
    }

    @Override
    public Integer findCountByDateAndPhone(String today, String phone) {
        return verificationCodeMapper.findCountByDateAndPhone(today, phone);
    }

    @Override
    public Map sendVerificationCode(String phone) throws ParseException, ClientException {
        //云之讯 同一个手机号1分钟内不能超过2条，24小时内验证类不能超过8条，通知类不能超过10条

        //验证一分钟内只能发2条短信
        String date = AppUtil.dateStr(2, new Date());
        Integer minNum = verificationCodeMapper.findCountByDateAndPhone(date, phone);
        if (minNum >= Const.SEND_CODE_MIN_COUNT) {
            return JsonData.fail(Const.SEND_CODE_MIN_ERROR);
        }

        //验证一天发送的数量，超过提示
        String today = DateUtil.today();
        Integer num = verificationCodeMapper.findCountByDateAndPhone(today, phone);
        if (num >= Const.SEND_CODE_DAY_COUNT) {
            return JsonData.fail(Const.SEND_CODE_DAY_ERROR);
        }

        //随机6位验证码
        String randomNumbers = RandomUtil.randomNumbers(6);

        SysVerificationCode code = new SysVerificationCode();
        code.setVcId(AppUtil.uuid());

        code.setVcPhone(phone);
        code.setVcCode(randomNumbers);
        code.setVcStatus(1);
        code.setCreateTime(new Date());
        //设置验证码有效时间
        String dateStr = AppUtil.calDate(5, Const.SEND_CODE_VALID_MIN);
        code.setValidTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(dateStr));

        //阿里大鱼
        AliSms aliSms = new AliSms();
        aliSms.setPhoneNumber(phone);
        aliSms.setSignName("摄影教育");
        aliSms.setTemplateCode(PropertiesUtil.getProperty("SEND_CODE_TEMPLATE_ID"));
        Map<String, String> map = Maps.newHashMap();
        map.put("code",randomNumbers);
        aliSms.setMap(map);
        SendSmsResponse sendSmsResponse = aliSmsService.sendSms(aliSms);

        if (!StringUtils.equals(sendSmsResponse.getCode(),"OK")){
            return JsonData.fail("发送失败");
        }

//        //使用第三方发短信 （云之讯）
//        UcpaasJson ucpaas = new UcpaasJson();
//        //使用发送的国际接口，需要添加国家代码
//        ucpaas.setTo("0086"+phone);
//        ucpaas.setParam(randomNumbers);
//        ucpaas.setTemplateId(TEMPLATE_ID);
//        Map map = ucpaasService.sendSmsInternational(ucpaas);
//        if (!map.get("code").equals(Const.SUCCESS_CODE)) {
//            return JsonData.fail("发送失败");
//        }

        //发送成功添加记录
        verificationCodeMapper.insertSelective(code);
        return JsonData.success(code);
    }
}
